package network;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;

import controller.ServerController;
import controller.impl.ServerControllerImpl;


/**
 * 模拟 TCP服务端
 * @author WUJA13
 *
 */
public class TCPServer {

	private int port = 8888;
	private ServerSocket server;
	private ServerController serverController;
	
	public TCPServer(){
		this.serverController = new ServerControllerImpl();
	}
	
	
	///获取端口信息
	public int getPort() {
		return port;
	}

	///设置端口信息，按情况重启服务
	public void setPort(int port) {
		this.port = port;
		if(this.isStarted()){
			this.restart();
		}
	}


	///启动
	public void start(){
		Socket client = null;
		try {
			this.server = new ServerSocket(this.port);
			client = this.server.accept();
			OutputStream out = client.getOutputStream();
			InputStream in = client.getInputStream();
			////处理与客户端之间的对话
			this.serverController.dealWithClient(in, out);
			in.close();
			out.close();
			client.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	///当前ServerSocket是否运作中
	public boolean isStarted(){
		return this.server.isClosed();
	}
	
	
	///重启
	public void restart(){
		try {
			if(this.isStarted())
			this.server.close();
			this.server = null;
		} catch (IOException e) {
			e.printStackTrace();
		}
		this.start();
	}
	
	///停止
	public void stop(){
		if (this.isStarted()) {
			try {
				this.server.close();
				this.server = null;
			} catch (IOException e) {
				e.printStackTrace();
			} 
		}
	}
	
}
